﻿using Microsoft.Extensions.Logging;
using JESAI.Application.Abstractions.Sys;
using JESAI.Application.Abstractions.Sys.Dtos;
using JESAI.AutoMapper.ObjectMapping;
using JESAI.Core.Attributes;
using JESAI.DDD.Services;
using JESAI.Platform.Domain.Sys.Entities;
using JESAI.Platform.Domain.Sys.Repositories;
using JESAI.Uow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.Application.Service.Sys
{
    [AppService]
    public class AuditLogService : ApplicationService, IAuditLogService
    {
        private readonly IAuditLogRepository _auditLogRepository;
        private readonly ILogger<AuditLogService> _logger;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        public AuditLogService(IAuditLogRepository auditLogRepository, ILogger<AuditLogService> logger,
           IUnitOfWorkManager unitOfWorkManager)
        {
            _auditLogRepository = auditLogRepository;
            _logger = logger;
            _unitOfWorkManager = unitOfWorkManager;
        }

        public void AddAuditLogAsync(AuditLogDto auditLogDto)
        {
            using (var uow = _unitOfWorkManager.CreateContext())
            {
                var entity = auditLogDto.MapTo<AuditLogEntity>();
                entity.Id = Guid.NewGuid().ToString();
                _auditLogRepository.Insert(entity);
                uow.Commit();
            }
        }

        public void UpdateAuditLogAsync(AuditLogDto auditLogDto)
        {
            //Task.Run(() =>
            //{
            using (var uow = _unitOfWorkManager.CreateContext())
            {
                try
                {

                    var entity = _auditLogRepository.GetFirst(x => x.ConnectionId == auditLogDto.ConnectionId);
                    if (entity != null)
                    {
                        entity.ResponseParams = auditLogDto.ResponseParams;
                        entity.RequestHandleTime = auditLogDto.RequestHandleTime;
                        entity.ResponseTime = auditLogDto.ResponseTime;

                        _auditLogRepository.Update(entity);
                    }
                    uow.Commit();
                }
                catch (Exception ex)
                {
                    uow.Rollback();
                    _logger.LogException(ex);
                }
            }
            //});
        }
    }
}
